package java6699.lesson10;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;

/**
 * @program: java_zzx
 * @description:
 * @author: zzx
 * @create: 2022-11-07 20:35
 **/
public class TextFile6699Controller {
    @FXML
    public Label lblSource;
    @FXML
    public Label lblTarget;
    @FXML
    public TextArea taText;

    private File sourceFile;
    private File targetFile;
    private FileChooser fc;//创建JavaFX文件选择器对话框

    @FXML
    public void selectSource(ActionEvent actionEvent) {
        taText.clear();
        lblSource.setText("");
        //使用FileChooser选择复制所需的源文件
        fc = fileChoose("请选择要复制的源文件");
        sourceFile = fc.showOpenDialog(new Stage());//显示文件选择器对话框
        lblSource.setText(sourceFile.getAbsolutePath());
    }

    @FXML
    public void selectTarget(ActionEvent actionEvent) {
        lblTarget.setText("");
        // 使用FileChooser选择复制所需的目标文件
        fc = fileChoose("请选择复制到哪个文件");
        targetFile = fc.showOpenDialog(new Stage());
        lblTarget.setText(targetFile.getAbsolutePath());
    }

    @FXML
    public void copyFile(ActionEvent actionEvent) {
        // 源文件和目标文件不为空执行
        if (sourceFile != null && targetFile != null) {
            // 使用Scanner读文本文件，用打印输出流写文本文件
            try (Scanner reader = new Scanner(sourceFile);
                 PrintStream writer = new PrintStream(targetFile)) {
                //每次读取清空taText数据
                taText.clear();
                //循环读数据，每次读一行
                String line;
                while (reader.hasNext()) {
                    line = reader.nextLine() + System.lineSeparator();
                    writer.print(line);
                    taText.appendText(line);
                }
            } catch (FileNotFoundException e) {
                taText.setText(e.getMessage());
            }
        }
    }

    private FileChooser fileChoose(String title) {
        // 初始化文件选择器
        fc = new FileChooser();
        fc.setTitle(title);
        fc.setInitialDirectory(new File("."));
        // 文件选择过滤器
        fc.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("文本文件", "*.txt"),
                new FileChooser.ExtensionFilter("所有文件", "*,*")
        );
        return fc;
    }
}
